package com.shsmi.util;

import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

@Component
@EnableScheduling
public class GenerateToken {
    public static String tokenStr;

    public static void main(String[] args) {
        generateToken();
        System.out.println("token----" + tokenStr);
    }

    @Scheduled(cron = "0 0 1 * * ?")
    public static void generateToken() {
        String OneMapHost = "http://10.87.94.143";
//        String OneMapHost = "http://10.108.3.36";

        //设置申请token所需的参数
        TokenInfo tokeninfo = new TokenInfo();
        //Clientid
        //该参数用于防止A系统请求生成的token被B系统盗用
        //A系统在请求服务器生成token时设置clientid为ref.http://www.a.com
        //A系统向服务器发出HTTP请求要求地图服务时，URL中以?token=...的形式传递token给服务器，同时浏览器在发出的HTTP请求的Request HEAD中自动设置Referer=http://www.a.com/map.html
        //服务器将收到的token反解得到clientid，将其与HTTP Request HEAD的Referer进行比较，如果两者一致则正常返回地图资源
        //假设B系统盗用了A系统的token向服务器请求地图资源
        //浏览器在发出的HTTP请求的Request HEAD中自动设置Referer=http://www.b.com/map.html
        //但是B系统提交的token反解出的clientid是www.a.com，与Referer的值www.b.com不一致，服务器将拒绝提供服务
        //请将127.0.0.1修改为实际域名或者IP
        tokeninfo.setClientid("ref.http://192.168.1.101");
        //token有效期【分钟】
        tokeninfo.setExpiration("14400");
        //请输入实际用户名
        tokeninfo.setUsername("smiuser");
//        tokeninfo.setUsername("lggwh");

        //请输入实际密码
        tokeninfo.setPassword("11111111");
//        tokeninfo.setPassword("Lggwh2001");

        //Token服务器地址
        tokeninfo.setTokenserverurl(OneMapHost + "/RemoteTokenServer");

        try {
            //申请token的HTTP请求形如http://x.x.x.x/RemoteTokenServer?request=getToken&username=xxx&password=yyy&clientid=ref.http://127.0.0.1&expiration=500
            URL url = new URL(tokeninfo.getTokenRequest());
            //urlConnection对象实际上是根据URL的请求协议(此处是http)生成的URLConnection类的子类HttpURLConnection
            //此处最好将其转化为HttpURLConnection类型的对象,以便用到HttpURLConnection更多的API
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //发出申请token的HTTP请求
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            //获取token
            while ((line = in.readLine()) != null) {
                buffer.append(line);
            }
            tokenStr = buffer.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
